var Gallery = {
	images: [],
	easterEgg:{name: 'easteregg', url:'assets/gallery/cn.jpg', url_bw:'assets/gallery/cnBW.jpg'},	
	
	
	init: function() {		
		this.loader = $('<div class="loader"></div>');
		this.thumbs = $('#sidebar-gallery');
		this.sidebar = $('#sidebar-container');
		this.sidebar.css('z-index', 1);
		this.loadHomepageData();
		$('#close-sidebar-gallery').bind('click', this.onHide);	
	},

	loadHomepageData: function() {
		$.ajax({
			//url: 'http://justinbieberdashboard.stage.mgroove-hosting.com/api/homepage',
			url: 'http://justinbieber.microgroove.com/api/homepage',
			dataType: 'jsonp',
			success: Gallery.onLoadHomepageDataComplete
		});
	},

	onLoadHomepageDataComplete: function(data) {
		var bgData = {};
		var countryExist = false;

		var thisCountry = (ipResponse == 'CA' || ipResponse == 'GB') ? ipResponse : 'US';
		//var thisCountry = 'GB';
		//ipResponse = 'GB';

		//Handle Touts
		for(var i=0; i<data.length; i++) {
			if(data[i].country == thisCountry) {
				var touts = data[i].touts;
				var ads = ['#ad-one', '#ad-two', '#ad-three'];
				for (var i = 0; i < touts.length; i++) {
					var url = touts[i].url;
						$(ads[i]).attr("href", url);

					var img = touts[i].image;
						$(ads[i]).css("background-image", "url('"+Gallery.prefix_url+"news/"+img+"')");
				}
			}
		}

		//Handle Backgrounds
		for(var i=0; i<data.length; i++) {
			if(data[i].country == thisCountry) {
				var images = data[i].backgrounds;
				countryExist = true;
				for(var ii=1; ii<=images.length; ii++) {
					if(ii % 2 == 0) {
						bgData.url_bw = images[ii-1].image;
						Gallery.images.push(bgData);
						bgData = {};
					} else {
						bgData.url = images[ii-1].image;
						bgData.link = images[ii-1].url;
					}
				}
			}

			if(i == (data.length - 1)) {
				if(countryExist == false) {
					var images = data[0].backgrounds;
					for(var ii=1; ii<=images.length; ii++) {
						if(ii % 2 == 0) {
							bgData.url_bw = images[ii-1].image;
							Gallery.images.push(bgData);
							bgData = {};
						} else {
							bgData.url = images[ii-1].image;
							bgData.link = images[ii-1].url;
						}
					}
				}
			}
		}

		Gallery.loadImages();
		Gallery.setDefaultBackground();
	},

	loadImages: function() {
		for(var i = 0; i<Gallery.images.length; i++) {
			var item = Gallery.images[i];
			var html = '<li class="thumb-holder">'+
				'<div class="thumb-image" style="background: url('+Gallery.prefix_url+'250/'+item.url+') no-repeat;">'+
				'<ul class="gallery-share" id="galleryShare">'+
					'<li class="downloadfb"><a href="/_local/images/billboards/fbbillboard_0'+i+'.jpg" target="_blank" class="download-billboard sequence" data-i="0">Download</a></li>'+
					'<li class="download"><a href="'+Gallery.prefix_url+'news/'+item.url+'" target="_blank" class="download-wallpaper sequence" data-i="0">Download</a></li>'+
					'<li class="share"><a href="#" class="share-wallpaper sequence" data-i="0">Share</a></li>'+
				'</ul>'+
				'</div>'+
				'</li>';
			var $htmlItem = $(html);
			$htmlItem.data('val', item);
			$('#thumbs').append($htmlItem);
		}

		$('.thumb-image').bind('click', Gallery.itemImageClick);
		$('.thumb-image').bind('mouseenter', Gallery.itemImageOver);
		$('.thumb-image').bind('mouseleave', Gallery.itemImageOut);
		$('.sequence').unbind('mouseenter').bind('mouseenter', Header.onNavItemOver);
		$('.sequence').unbind('mouseleave').bind('mouseleave', Header.onNavItemOut);
		$('.share-wallpaper').bind('click', Gallery.onShareEvent);
		$('.download-wallpaper').bind('click', Gallery.onDownloadEvent);
		$('.download-billboard').bind('click', Gallery.onDownloadEvent);
	},

	itemImageClick: function() {
		Utility.gaTrackEvent('Backgrounds', 'Change');
		var data = $(this).parent().data();
		Gallery.showItem(data.val);
	},

	itemImageOver: function(event) {
		var $galleryShareBtns = $(this).children();

		if(!$galleryShareBtns.is(':animated')) {
			$galleryShareBtns.fadeIn(200);
		}
	},

	itemImageOut: function(event) {
		$(this).children().fadeOut(200);
	},

	showItem: function(item, isEasterEgg) {
		var url = (!isEasterEgg || isEasterEgg == undefined) ? Gallery.prefix_url + 'news/'+ item.url : Gallery.localPrefixUrl + item.url;
		var bwurl = (!isEasterEgg || isEasterEgg == undefined) ? Gallery.prefix_url + 'news/'+ item.url_bw :  Gallery.localPrefixUrl + item.url;
		//opaque current bg while it loads the next
		var currentBGs = $('.bg-container-item');
		//remove listeners
		$('img', currentBGs).off('load');
		
		if(BrowserDetect.supportTransition()){
			currentBGs.addClass('bg-to-remove');
		}else{
			currentBGs.addClass('bg-to-remove-ie');
			$('img',currentBGs).fadeTo("fast",0.5);
			//currentBGs.fadeOut(200);
		}
		
		//create divs
		var newContainer = $('<div class="bg-container-item bg-current"></div>');
		newContainer.appendTo('#background-holder');
		Gallery.loader.appendTo('#background-holder');
		var bwImage = $('<img />');
		bwImage.data({
			'val': url+"?random="+Math.floor(Math.random()*10000), 
			'link': item.link
		});
		
		var colorImage = $('<img class="bg-image" width="1920" height="1080" />');

		if(item.name == 'easteregg') {
			bwImage.css({marginTop: '-160px'});
			colorImage.css({marginTop: '-160px'});
		}

		colorImage.appendTo(newContainer);
		bwImage.appendTo(newContainer);
		
		bwImage.load(Gallery.onBWImageLoad);
		bwImage.attr('src', bwurl+"?random="+Math.floor(Math.random()*10000));
	},

	setDefaultBackground: function() {
		var item = Gallery.images[0];
		var url = Gallery.prefix_url + 'news/'+ item.url;
		
		var newContainer = $('<div class="bg-container-item bg-current bg-container-item-center"></div>');
		newContainer.appendTo('#background-holder');
		Gallery.loader.appendTo('#background-holder');
			
		var colorImage = $('<img class="bg-image" width="1920" height="1080" />');
		colorImage.appendTo(newContainer);
		
		if(!BrowserDetect.supportTransition()){
			colorImage.css({display:'none'});
		}
		
		colorImage.load(Gallery.onMainImageLoad);
		colorImage.attr('src', url);
		
		var link = item.link;

		if(link != '') {
			var html = '<a href="'+link+'" class="background-link" id="backgroundLink" target="_blank"></a>';
			$('#background-holder').prepend(html);
		}	
	},

	removeLeftBackgrounds: function() {
		$('.bg-container-item-left, .bg-container-item-left-ie').remove();
	},

	onBWImageLoad: function() {
		$(this).off('load');
		Gallery.loader.remove();
		//transition out all bg
		var currentBGs = $('.bg-to-remove, .bg-to-remove-ie');
		currentBGs.removeClass('bg-current');
		
		var newContainer = $('.bg-current');
		colorImage = $('.bg-image', newContainer);
		colorImage.load(Gallery.onMainImageLoad);
		colorImage.attr('src', $(this).data().val);

		var link = $(this).data().link;

		if($('#backgroundLink').length > 0) {
			$('#backgroundLink').remove();
		}

		if(link != '') {
			var html = '<a href="'+link+'" class="background-link" id="backgroundLink" target="_blank"></a>';
			$('#background-holder').prepend(html);
		}
		
		if(BrowserDetect.supportTransition()){
			currentBGs.addClass('bg-container-item-left');
			newContainer.addClass('bg-container-item-center');
		}else{
			colorImage.css({display:'none'});
			
			currentBGs.addClass('bg-container-item-left-ie');
			currentBGs.animate({left:-2000}, 800);
			
			newContainer.addClass('bg-container-item-center-ie');
			newContainer.animate({left:0}, 800);
		}
		//delay to remove them until they are offscreen
		setTimeout(Gallery.removeLeftBackgrounds , 1000);
	},

	onShareEvent: function(event) {
		var data = {
			type: 'gallery',
			link: 'http://justinbiebermusic.com/#/gallery',
			tweet: 'Download official Justin Bieber backgrounds here:',
			fb: {
				title: 'Justin Bieber Backgrounds',
				image: 'http://justinbiebermusic.com/assets/fbThumbnail.jpg?v=2',
				desc: 'Download official Justin Bieber backgrounds here:',
				caption: ''
			}
		};

		Utility.gaTrackEvent('Backgrounds', 'Share');
		ShareOverlay.launch(data);

		return false;
	},

	onDownloadEvent: function(event) {
		Utility.gaTrackEvent('Backgrounds', 'Download');
		window.open(this.href);

		return false;
	},

	onMainImageLoad: function() {
		$(this).off('load');
		setTimeout(Gallery.showColorImage, 600);

	},

	showColorImage: function() {
		if(BrowserDetect.supportTransition()){
			$('.bg-image').addClass('bg-show');
		}else{
			$('.bg-image').fadeIn(800);
		}
		
	},

	show: function(event) {
		var offsetTop = $('#top').offset().top + 64;
		Gallery.thumbs.removeClass('gallery-sidebar-hide').addClass('gallery-sidebar-show');
		Gallery.sidebar.css({'z-index': 10, top: offsetTop+'px'}).addClass('sidebar-overflow active-window');
		River.allowResize = false;	
		River.showBackToTop = false;
		River.backToTop.fadeOut(200);	
		Utility.gaTrackEvent('Backgrounds', 'Open');
	},

	hide: function() {
		Gallery.thumbs.removeClass('gallery-sidebar-show').addClass('gallery-sidebar-hide');
		Gallery.sidebar.css('z-index', 1).removeClass('sidebar-overflow active-window');
		Utility.gaTrackEvent('Backgrounds', 'Close');
	},

	onHide: function(event) {
		Gallery.hide();
		River.show();

		event.preventDefault();
	},

	onresize: function(h) {
		Gallery.sidebar.css({height: h+'px'});
	}
};